<?php

declare(strict_types=1);

namespace App\CustHub\Listener;

use App\CustHub\Event\RoomInviteAcceptTrigger;
use App\CustHub\Service\ChRoomInviteAcceptConfigService;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;
use function FriendsOfHyperf\Lock\lock;

#[Listener]
class RoomInviteAcceptListener implements ListenerInterface
{

    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            RoomInviteAcceptTrigger::class,
        ];
    }


    public function process(object $event): void
    {
        $lock = lock('room_invite_accept:'.$event->roomId.md5(json_encode($event->inviteData)),4);
        try {
            $lock->block(2);
            $this->container->get(ChRoomInviteAcceptConfigService::class)->handle($event->robot,$event->roomId,$event->inviteData);
        } catch (LockTimeoutException $e) {
        } finally {
            $lock->release();
        }
    }

}